package com.mtao.impl;

import com.mtao.mapper.SysRoleMapper;
import com.mtao.mapper.SysUserMapper;
import com.mtao.entity.SysRole;
import com.mtao.SysRoleService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 获取角色列表
     * @return
     */
    @Override
    public List<SysRole> findRoleList() {
        List<SysRole> roles = sysRoleMapper.findRoles();
        return roles;
    }

    /**
     * 获取角色列表
     * @param sysRole
     * @return
     */
    @Override
    public void addRole(SysRole sysRole) {
        sysRole.setCreateTime(LocalDateTime.now());
        sysRole.setUpdateTime(LocalDateTime.now());
        sysRoleMapper.addRoles(sysRole);
    }

    /**
     * 通过用户ID获取当前用户角色
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> getRoleByUserId(Integer userId) {
        List<SysRole> sysRoles = sysRoleMapper.getRoleByUserId(userId);
        return sysRoles;
    }

    /**
     * 获取用户当前角色列表
     * @param userId
     * @return
     */
    @Override
    public List<GrantedAuthority> getRolesByUser(Integer userId) {
        Set<String> permissions = new HashSet<>();
        List<SysRole> roleList = sysRoleMapper.getRoleByUserId(userId);
        if (!CollectionUtils.isEmpty(roleList)){
            for (SysRole sysRole : roleList) {
                permissions.add(sysRole.getRoleCode());
            }
        }
        return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    /**
     * 删除角色
     * @param id
     * @return
     */

    @Override
    public void deleteRole(Integer id) {
        System.out.println("id="+id);
        sysRoleMapper.delete(id);
    }
    /**
     * 查询角色名是否存在
     * @param roleName
     * @return
     */
    @Override
    public boolean queryRoleName(String roleName) {
       SysRole sysRoles=sysRoleMapper.findName(roleName);
        System.out.println("sysRoles"+sysRoles);
       return sysRoles!=null;
    }
    /**
     * 更新角色
     * @param sysRole
     * @return
     */

    @Override
    public void updateRole(SysRole sysRole) {
        sysRoleMapper.updateRole(sysRole);
    }
}
